package com.evaluationSystem.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.evaluationSystem.entity.*;
import com.evaluationSystem.entity.dto.Fraction;
import com.evaluationSystem.entity.dto.QuestionnaireDto;
import com.evaluationSystem.entity.dto.ScoreDto;
import com.evaluationSystem.entity.vo.*;
import com.evaluationSystem.exception.EvaluationException;
import com.evaluationSystem.mapper.*;
import com.evaluationSystem.service.ScoreService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class ScoreImpl implements ScoreService {
    private final ScoreMapper scoreMapper;
    private final AppraiseMapper appraiseMapper;
    private final WeightMapper weightMapper;
    private final DimensionMapper dimensionMapper;
    private final QuestionnaireMapper questionnaireMapper;
    private final WeighstServiceCopy weighstServiceCopy;
    private final FractionMapper fractionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveScoring(Score score) {
        QuestionnaireDto questionnaireDto = new QuestionnaireDto();
        questionnaireDto.setQuestionDeadTime(new Date());
        List<Questionnaire> list = questionnaireMapper.getQuestionList(questionnaireDto);
        if (list.size() == 0) {
            throw new EvaluationException("问卷已关闭!");
        }

        Score scoring = scoreMapper.selectScoring(score.getUserId(), score.getReviewerId(), score.getQuestionId());
        if (scoring != null) {
//            scoreMapper.deleteScoring(score);
            throw new EvaluationException("问卷已提交，请勿重复提交!");
        }

        Appraise appraise1 = new Appraise();
        appraise1.setAppraiserPhone(score.getUserId());
        appraise1.setQuestionId(score.getQuestionId());
        appraise1.setAppraiserName(score.getUserName());
        appraise1.setAssessedName(score.getReviewerName());
        double quanzhong = weighstServiceCopy.getQuanzhong(score.getUserId(), score.getQuestionId(), score.getReviewerName());

        double v = saveScorResult(score, quanzhong);
        Fraction fraction = new Fraction();
        fraction.setFenshu(String.valueOf(v));
        fraction.setAssessedName(score.getReviewerName());
        fraction.setAssessedId(score.getReviewerId());
        fraction.setAppraiserName(score.getUserName());
        fraction.setAppraiserId(score.getUserId());
        fraction.setAppraiserPhone(score.getUserId());
        fraction.setQuestionId(score.getQuestionId());
        fractionMapper.insertFraction(fraction);

        scoreMapper.saveScoring(score);

        Appraise appraise = new Appraise();
        appraise.setAppraiseStatus(1);
        appraise.setAppraiserId(score.getUserId());
        appraise.setQuestionId(score.getQuestionId());
        appraise.setAssessedId(score.getReviewerId());
        appraiseMapper.updateAppraise(appraise);

        AnalyseOwnVo evaluateObject = appraiseMapper.getEvaluateObject(appraise);
        List<AnalyseOwnVo.AppraiserUser> appraiserUser = null;
        if (evaluateObject != null) {
            appraiserUser = evaluateObject.getAppraiserUser();
        } else {
            System.out.println("空指针异常");
        }
        long count = appraiserUser.stream().filter(res -> StringUtils.isNotBlank(res.getUserScore())).count();
        int status = 0;
        if (count == appraiserUser.size()) {
            status = 1;
        } else if (count < appraiserUser.size()) {
            status = 2;
        }

        Appraise appraise2 = new Appraise();
        appraise2.setAppraiserId(score.getUserId());
        appraise2.setQuestionId(score.getQuestionId());
        appraise2.setCompleteStatus(status);
        appraiseMapper.updateAppraise(appraise2);

    }

    private Weight getWeight(String questionId, String assessedId) {
        List<Weight> weights = weightMapper.getInfo(questionId);//获取权重

        Appraise appraiseDto = new Appraise();
        appraiseDto.setQuestionId(questionId);
        appraiseDto.setAssessedId(assessedId);
        List<Appraise> appraiseList = appraiseMapper.countAppraiseList(appraiseDto);//以问卷id和被评人找出评价关系

        appraiseList.forEach(appraise -> {
            if (Objects.isNull(appraise.getAppraiseTiesId())) {
                String appraiseTies = appraise.getAppraiseTies();
                // 解析 appraiseTies 字段中的数字
                int appraiseTiesId = Integer.parseInt(appraiseTies.replaceAll("\\D", ""));
                appraise.setAppraiseTiesId(appraiseTiesId);

                // 更新数据库中的 appraise 对象
                appraiseMapper.updateAppraise(appraise);
            }
        });

        return filterWeight(weights, appraiseList);
    }

    //    private Weight filterWeight(List<Weight> weights, List<Appraise> appraiseList) {
//
//        Set<Integer> collect = appraiseList.stream().filter(res ->
//                StringUtils.isNotBlank(res.getUserScore())).map(res ->
//                Integer.valueOf(res.getAppraiseTiesId())).collect(Collectors.toSet());
//        System.out.println(collect);
//        Weight weightVo = null;
//        for (Weight weight : weights) {
//            boolean b = true;
//            if (collect.contains(1)) {
//                if (weight.getLevel1() == 0) { b = false; continue; }
//            } else {
//                if (weight.getLevel1() != 0) { b = false; continue; }
//            }
//            if (collect.contains(2)) {
//                if (weight.getLevel2() == 0) { b = false; continue; }
//            } else {
//                if (weight.getLevel2() != 0) { b = false; continue; }
//            }
//            if (collect.contains(3)) {
//                if (weight.getLevel3() == 0) { b = false; continue; }
//            } else {
//                if (weight.getLevel3() != 0) { b = false; continue; }
//            }
//            if (collect.contains(4)) {
//                if (weight.getLevel4() == 0) { b = false; continue; }
//            } else {
//                if (weight.getLevel4() != 0) { b = false; continue; }
//            }
//            if (collect.contains(5)) {
//                if (weight.getLevel5() == 0) { b = false; continue; }
//            } else {
//                if (weight.getLevel5() != 0) { b = false; continue; }
//            }
//            if (collect.contains(6)) {
//                if (weight.getLevel6() == 0) { b = false; continue; }
//            } else {
//                if (weight.getLevel6() != 0) { b = false; continue; }
//            }
//            if (collect.contains(7)) {
//                if (weight.getLevel7() == 0) { b = false; continue; }
//            } else {
//                if (weight.getLevel7() != 0) { b = false; continue; }
//            }
//            if (collect.contains(8)) {
//                if (weight.getLevel8() == 0) { b = false; continue; }
//            } else {
//                if (weight.getLevel8() != 0) { b = false; continue; }
//            }
//            if (b) {
//                weightVo = weight;
//                break;
//            }
//        }
//        return weightVo;//获取权重
//    }
    private Weight filterWeight(List<Weight> weights, List<Appraise> appraiseList) {
        Set<Integer> collect = appraiseList.stream()
                .filter(res -> StringUtils.isNotBlank(res.getUserScore()))
                .map(res -> Integer.valueOf(res.getAppraiseTiesId()))
                .collect(Collectors.toSet());

        System.out.println(collect);

        Weight weightVo = null;

        for (Weight weight : weights) {
            boolean b = true;

            for (Integer level : collect) {
                int levelValue = getLevelValue(weight, level);
                if (levelValue == 0) {
                    b = false;
                    break;
                }
            }

            if (b) {
                weightVo = weight;
                break;
            }
        }

        return weightVo;
    }

    private int getLevelValue(Weight weight, int level) {
        switch (level) {
            case 1:
                return weight.getLevel1();
            case 2:
                return weight.getLevel2();
            case 3:
                return weight.getLevel3();
            case 4:
                return weight.getLevel4();
            case 5:
                return weight.getLevel5();
            case 6:
                return weight.getLevel6();
            case 7:
                return weight.getLevel7();
            case 8:
                return weight.getLevel8();
            default:
                return 0;
        }
    }

    public Map<String, Object> getAnalyseList(ScoreDto scoreDto) {
        Map<String, Object> map = new HashMap<>();

        List<AnalyseListVo> analyseListVos = appraiseMapper.appraiseAnalyseList(scoreDto);
        List<Weight> weights = weightMapper.getInfo(scoreDto.getQuestionId());

        Appraise appraiseDto = new Appraise();
        appraiseDto.setQuestionId(scoreDto.getQuestionId());
        List<Appraise> appraiseList = appraiseMapper.countAppraiseList(appraiseDto);

        System.out.println(analyseListVos);

        analyseListVos.forEach(res -> {
            for (AnalyseListVo.AppraiserUser appraiserUser : res.getAppraiserUser()) {
                Integer appraiseTiesId = appraiserUser.getAppraiseTiesId();
                String appraiseTies = appraiserUser.getAppraiseTies();
                // 解析 appraiseTies 字段中的数字
                Integer appraiseTiesIds = Integer.parseInt(appraiseTies.replaceAll("\\D", ""));

                appraiserUser.setAppraiseTiesId(appraiseTiesIds);
                System.out.println(appraiserUser);
            }


            List<Appraise> collect = appraiseList.stream().filter(appraise -> res.getAssessedId().equals(appraise.getAssessedId()) && StringUtils.isNotBlank(appraise.getUserScore())).collect(Collectors.toList());

            collect.forEach(appraise -> {
                if (Objects.isNull(appraise.getAppraiseTiesId())) {
                    String appraiseTies = appraise.getAppraiseTies();
                    // 解析 appraiseTies 字段中的数字
                    int appraiseTiesId = Integer.parseInt(appraiseTies.replaceAll("\\D", ""));
                    appraise.setAppraiseTiesId(appraiseTiesId);
                }
            });


            Weight weight = filterWeight(weights, collect);
            System.out.println(weight);
            System.out.println(weights);
            System.out.println(collect);

            long completeNum = 0;
            double totalScore = 0.0;
            for (AnalyseListVo.AppraiserUser appraiserUser : res.getAppraiserUser()) {
                if (StringUtils.isNotBlank(appraiserUser.getUserScore())) {
                    completeNum++;
                    if (weight != null) {
                        long avgSum = res.getAppraiserUser().stream().filter(appraiser -> appraiserUser.getAppraiseTiesId().equals(appraiser.getAppraiseTiesId()) && StringUtils.isNotBlank(appraiser.getUserScore())).count();
                        double percentage = percentage(weight, appraiserUser.getAppraiseTiesId());
                        List<String> strArray = Arrays.asList(appraiserUser.getUserScore().split(","));
                        int sum = 0;
                        for (String str : strArray) {
                            try {
                                sum += Integer.parseInt(str);
                            } catch (NumberFormatException e) {
                                continue; // 如果出现异常，跳过当前数据
                            }
                        }
                        totalScore += (sum * percentage) / avgSum;
                    }
                }
            }
            res.setAppraiserUserCount(completeNum + "/" + res.getAppraiserUser().size());
            res.setScoreTotal((double) Math.round(totalScore * 10000) / 10000);
        });

        map.put("list", analyseListVos);

        return map;
    }

    // todo 计算 分数的地方 需要重写改为 a的权重×打分分值换算的百分制+100*（1-a的权重） 这种方式计算

    public List<AnalyseListVo> getAnalyseLists(ScoreDto scoreDto , String ppraise ) {
        Map<String, Object> map = new HashMap<>();
        List<AnalyseListVo> maps = null;

        List<AnalyseListVo> analyseListVos = appraiseMapper.appraiseAnalyseList(scoreDto);
        List<Weight> weights = weightMapper.getInfo(scoreDto.getQuestionId());

        Appraise appraiseDto = new Appraise();
        appraiseDto.setQuestionId(scoreDto.getQuestionId());
        List<Appraise> appraiseList = appraiseMapper.countAppraiseList(appraiseDto);
        List<AnalyseListVo.AppraiserUser >appraiserUser1 = appraiseMapper.selectListquestionId(scoreDto.getQuestionId());

        analyseListVos.forEach(res -> {
            List<AnalyseListVo.AppraiserUser> appraiserUsers = res.getAppraiserUser();
            if (appraiserUsers == null || appraiserUsers.isEmpty()) {
                appraiserUsers = appraiserUser1;
                if (appraiserUsers == null || appraiserUsers.isEmpty()) {
                    return;
                }
            }

            for (AnalyseListVo.AppraiserUser appraiserUser : res.getAppraiserUser()) {
                Integer appraiseTiesId = appraiserUser.getAppraiseTiesId();
                String appraiseTies = appraiserUser.getAppraiseTies();
                Integer appraiseTiesIds = Integer.parseInt(appraiseTies.replaceAll("\\D", ""));
                appraiserUser.setAppraiseTiesId(appraiseTiesIds);
            }

            List<Appraise> collect = new ArrayList<>();
            for (Appraise appraise : appraiseList) {
                if (res.getAssessedId().equals(appraise.getAssessedId()) && StringUtils.isNotBlank(appraise.getUserScore())) {
                    collect.add(appraise);
                }
            }
//            Weight weight = filterWeight(weights, collect);

            long completeNum = 0;
            double totalScore = 0.0;
            List<AnalyseListVo.AppraiserUser> appraiserUser2 = res.getAppraiserUser();

            for (AnalyseListVo.AppraiserUser appraiserUser : appraiserUser2) {
                System.out.println("开始计算总分");
                if (StringUtils.isNotBlank(appraiserUser.getUserScore()) ) {
                    System.out.println("用户得分不为空");
                    completeNum++;
//                    if (weight != null) {
//                        System.out.println("权重也不为空");
//                        List<Dimension> zf = appraiseMapper.selezf(ppraise);
//                        long avgSum = calculateFirstScores(zf);
//
//                        double percentage = percentage(weight, appraiserUser.getAppraiseTiesId());
//                        List<String> strArray = Arrays.asList(appraiserUser.getUserScore().split(","));
//                        // 得到不计算权重的总分
//                        System.out.println("进入计算方法");
//                        int sum = 0;
//                        for (String str : strArray) {
//                            System.out.println("str：" + str);
//
//                            try {
//                                sum += Integer.parseInt(str);
//                            } catch (NumberFormatException e) {
//                                continue; // 如果出现异常，跳过当前数据
//                            }
//                        }
//                        System.out.println("percentage：" + percentage);
//                        System.out.println("sum：" + sum);
//                        System.out.println("avgSum：" + avgSum);
//                        totalScore = percentage * sum / avgSum * 100  + 100 * (1 - percentage);
//                        System.out.println("totalScore：" + totalScore);
//                        res.setScoreTotal(totalScore);
//                        res.setQuanzhong(percentage);
//
//                    }
                }
            }
            res.setAppraiserUserCount(completeNum + "/" + res.getAppraiserUser().size());
        });
        return analyseListVos;
    }

    @Override
    public Map<String, Object> scoringAnalysePage(ScoreDto scoreDto) {
        int index = scoreDto.getPage() == 0 ? 0 : scoreDto.getPage() - 1;

        scoreDto.setPage(index * scoreDto.getLimit());

        Map<String, Object> map = getAnalyseList(scoreDto);

        map.put("total", appraiseMapper.getAppraiseAnalyseCount(scoreDto.getQuestionId()));
        return map;
    }
    private static long calculateFirstScores(List<Dimension> dimensions) {
        long totalSum = 0;

        for (Dimension dimension : dimensions) {
            String assessScore = dimension.getAssessScore();

            if (!StringUtils.isEmpty(assessScore)) {
                try {
                    int firstScore = Integer.parseInt(assessScore.split(",")[0]);
                    totalSum += firstScore;
                } catch (NumberFormatException | IndexOutOfBoundsException e) {
                    // 处理可能的异常情况
                }
            }
        }

        return totalSum;
    }
    @Override
    public List<ScoreVo> scoringAnalyse(@NotNull ScoreDto scoreDto) {

        scoreDto.setPage(null);
        scoreDto.setLimit(null);

        Map<String, Object> map = getAnalyseList(scoreDto);
        List<AnalyseListVo> list = (List<AnalyseListVo>) map.get("list");

        List<ScoreVo> scoreVos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ScoreVo scoreVo = new ScoreVo();
            scoreVo.setColumNo(i + 1);
            scoreVo.setDeptName(list.get(i).getAssessedDept());
            scoreVo.setReviewerName(list.get(i).getAssessedName());
            scoreVo.setPeopleNumber(list.get(i).getAppraiserUserCount());
            scoreVo.setReviewerScore(list.get(i).getScoreTotal());
            scoreVos.add(scoreVo);
        }

        return scoreVos;
    }

    @Override
    public AnalyseInfoVo getAnalyseInfo(ScoreDto scoreDto) {
        AnalyseInfoVo analyseInfo = appraiseMapper.getAnalyseInfo(scoreDto);
        if (isAnalyseInfoNull(analyseInfo)) {
            System.out.println("无数据返回："+true);
        }else {
            System.out.println("有数据返回："+false);

        }
//        List<WeightDataVo.WeightDataList> weight = getWeight(scoreDto.getQuestionId(), scoreDto.getAssessedId());
        Weight weight = getWeight(scoreDto.getQuestionId(), scoreDto.getAssessedId());

        analyseInfo.setWeight(weight);
        System.out.println("结果是：" + analyseInfo);
        return analyseInfo;
    }
    public boolean isAnalyseInfoNull(AnalyseInfoVo analyseInfo) {
        return analyseInfo == null;
    }
    @Override
    public Map<String, Object> scoringDetail(ScoreDto scoreDto) {
        Map<String, Object> map = new HashMap<>();

        AnalyseDetailVo scoringDetail = appraiseMapper.getScoringDetail(scoreDto);

        System.out.println(scoringDetail);

        Weight weight = getWeight(scoreDto.getQuestionId(), scoringDetail.getAssessedId());

        List<Dimension> dimension = dimensionMapper.getDimension(scoreDto.getQuestionId());
        List<String> columns = dimension.stream().map(res -> res.getAssessDetail()).collect(Collectors.toList());
        columns.add(0, "评估人与被评估人关系");
        columns.add("加权平均分");
        List<Map<String, Object>> dataList = new ArrayList<>();

        Map<String, Object> row1 = new HashMap<>();
        Map<String, Object> row2 = new HashMap<>();
        Map<String, Object> row3 = new HashMap<>();
        Map<String, Object> row4 = new HashMap<>();
        Map<String, Object> row5 = new HashMap<>();
        Map<String, Object> row6 = new HashMap<>();
        Map<String, Object> row7 = new HashMap<>();
        Map<String, Object> row8 = new HashMap<>();

        row1.put("appraise_tiesId", 1);
        row1.put("0", "权重1");
        row2.put("appraise_tiesId", 2);
        row2.put("0", "权重2");
        row3.put("appraise_tiesId", 3);
        row3.put("0", "权重3");
        row4.put("appraise_tiesId", 4);
        row4.put("0", "权重4");
        row5.put("appraise_tiesId", 5);
        row5.put("0", "权重5");
        row6.put("appraise_tiesId", 6);
        row6.put("0", "权重6");
        row7.put("appraise_tiesId", 7);
        row7.put("0", "权重7");
        row8.put("appraise_tiesId", 8);
        row8.put("0", "权重8");

        dataList.add(row1);
        dataList.add(row2);
        dataList.add(row3);
        dataList.add(row4);
        dataList.add(row5);
        dataList.add(row6);
        dataList.add(row7);
        dataList.add(row8);

        for (Map<String, Object> stringObjectMap : dataList) {
            Integer appraiseTiesId = (Integer) stringObjectMap.get("appraise_tiesId");
            // todo
            long totalUser = scoringDetail.getAppraiserUser().stream().filter(res -> appraiseTiesId.equals(res.getAppraiseTiesId()) && StringUtils.isNotBlank(res.getUserScore())).count();//该级别评价总人数
            double totalScore = 0.0;//该级别评价总分
            for (int i = 0; i < dimension.size(); i++) {
                double score = 0.0;//该级别评价题目总分
                for (AnalyseDetailVo.AppraiserUser appraiserUser : scoringDetail.getAppraiserUser()) {
                    String appraiseTies = scoringDetail.getAppraiserUser().get(0).getAppraiseTies();
                    String apid = appraiseTies.substring(2);
                    int appId = Integer.parseInt(apid);
                    appraiserUser.setAppraiseTiesId(appId);
                    if (StringUtils.isNotBlank(appraiserUser.getUserScore()) && appraiseTiesId.equals(appraiserUser.getAppraiseTiesId())) {
                        try {
                            int userScore = Integer.parseInt(appraiserUser.getUserScore().split(",")[i]);
                            score += userScore;
                        } catch (NumberFormatException e) {
                            // 如果无法转换为整数，则跳过该项
                            continue;
                        }
                    }

                }
                totalScore += score;
                stringObjectMap.put(String.valueOf(i + 1), score);
            }
            double weightedAverage = 0.0;
            if (weight != null) {
                double percentage = percentage(weight, appraiseTiesId);//找出评价人对应的权重
                if (totalUser == 0) {
                    totalUser = 1;
                }
                double sum = (totalScore * percentage) / totalUser;
                weightedAverage = (double) Math.round(sum * 10000) / 10000;//加权平均分=该级别评价总分/该级别评价总人数*加权百分比
            }
            stringObjectMap.put(String.valueOf(dimension.size() + 1), weightedAverage);
        }

        map.put("columns", columns);
        map.put("dataList", dataList);

        return map;
    }

    @Override
    public Map<String, Object> scoringSubsidiary(ScoreDto scoreDto) {
        Map<String, Object> map = new HashMap<>();

        AnalyseDetailVo scoringDetail = appraiseMapper.getScoringDetail(scoreDto);

        List<Dimension> dimensionList = dimensionMapper.getDimension(scoreDto.getQuestionId());
        List<String> columns = new ArrayList<>();
        columns.add("评估人");
        columns.add("评估人与被评估人关系");
        for (Dimension dimension : dimensionList) {
            columns.add(dimension.getAssessDetail());
        }
        List<Map<String, Object>> dataList = new ArrayList<>();

        for (AnalyseDetailVo.AppraiserUser appraiserUser : scoringDetail.getAppraiserUser()) {
            Map<String, Object> row = new HashMap<>();
            row.put("0", appraiserUser.getAppraiserName());
            row.put("1", appraiserUser.getAppraiseTies());
            for (int i = 0; i < dimensionList.size(); i++) {
                if (StringUtils.isNotBlank(appraiserUser.getUserScore())) {
                    try {
                        row.put(String.valueOf(i + 2), Integer.parseInt(appraiserUser.getUserScore().split(",")[i]));
                    } catch (NumberFormatException e) {
                        row.put(String.valueOf(i + 2), appraiserUser.getUserScore().split(",")[i]);
                    }
                } else {
                    row.put(String.valueOf(i + 2), "");
                }
            }
            dataList.add(row);
        }

        map.put("columns", columns);
        map.put("dataList", dataList);

        return map;
    }

    @Override
    public void scoringExport(HttpServletResponse response, ScoreDto scoreDto) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=Detail.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                // 注册策略
                .registerWriteHandler(new SimpleColumnWidthStyleStrategy(25)) // 简单的列宽策略，列宽20
//                .registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 25)) // 简单的行高策略：头行高，内容行高
                .build();

        //第一张表
        WriteSheet writeSheet1 = EasyExcel.writerSheet(0, "sheet1").head(ScoreVo.class).build();
        excelWriter.write(scoringAnalyse(scoreDto), writeSheet1);

        //第二张表
        Map<String, Object> scoringDetailMap = scoringDetail(scoreDto);
        List<String> columns1 = (List<String>) scoringDetailMap.get("columns");
        List<Map<String, Object>> dataList1 = (List<Map<String, Object>>) scoringDetailMap.get("dataList");
        List<List<String>> columns1Excel = new ArrayList<>();
        List<List<Object>> dataList1Excel = new ArrayList<>();
        // 组装Excel插件需要的标题格式
        for (String s : columns1) {
            columns1Excel.add(Arrays.asList(s));
        }
        // 组装Excel插件需要的表格格式
        for (Map<String, Object> map : dataList1) {
            List<Object> maps = new ArrayList<>();
            for (int i = 0; i < columns1.size(); i++) {
                maps.add(map.get(String.valueOf(i)));
            }
            dataList1Excel.add(maps);
        }
        WriteSheet writeSheet2 = EasyExcel.writerSheet(1, "sheet2").head(columns1Excel).build();
        excelWriter.write(dataList1Excel, writeSheet2);

        //第三张表
        Map<String, Object> scoringSubsidiaryMap = scoringSubsidiary(scoreDto);
        List<String> columns2 = (List<String>) scoringSubsidiaryMap.get("columns");
        List<Map<String, Object>> dataList2 = (List<Map<String, Object>>) scoringSubsidiaryMap.get("dataList");
        List<List<String>> columns2Excel = new ArrayList<>();
        List<List<Object>> dataList2Excel = new ArrayList<>();
        // 组装Excel插件需要的标题格式
        for (String s : columns2) {
            columns2Excel.add(Arrays.asList(s));
        }
        // 组装Excel插件需要的表格格式
        for (Map<String, Object> map : dataList2) {
            List<Object> maps = new ArrayList<>();
            for (int i = 0; i < columns1.size(); i++) {
                maps.add(map.get(String.valueOf(i)));
            }
            dataList2Excel.add(maps);
        }
        WriteSheet writeSheet3 = EasyExcel.writerSheet(2, "sheet3").head(columns2Excel).build();
        excelWriter.write(dataList2Excel, writeSheet3);
        excelWriter.finish();
    }

    @Override
    public double saveScorResult(Score score,Double quanzhong) {
        ScoreDto scoreDto = new ScoreDto();
        scoreDto.setQuestionId(score.getQuestionId());
        List<AnalyseListVo> analyseListVos = appraiseMapper.appraiseAnalyseList(scoreDto);
        List<Weight> weights = weightMapper.getInfo(scoreDto.getQuestionId());

        Appraise appraiseDto = new Appraise();
        appraiseDto.setQuestionId(scoreDto.getQuestionId());
        List<Appraise> appraiseList = appraiseMapper.countAppraiseList(appraiseDto);
        Appraise matchedAppraise = appraiseList.stream()
                .filter(appraise ->
                        appraise.getAssessedName().equals(score.getReviewerName()) &&
                                appraise.getAssessedId().equals(score.getReviewerId())
                )
                .findFirst()
                .orElse(null);

        List<Appraise> matchedAppraiseList = new ArrayList<>();
        if (matchedAppraise != null) {
            matchedAppraiseList.add(matchedAppraise);
        }

        AnalyseListVo.AppraiserUser appraiserUser = new AnalyseListVo.AppraiserUser();
        Integer appraiseTiesId = null;
        String appraiseTies = matchedAppraise.getAppraiseTies();

        if (appraiseTies != null) {
            String numericString = appraiseTies.replaceAll("\\D", "");
            if (!numericString.isEmpty()) {
                appraiseTiesId = Integer.parseInt(numericString);
            }
        }
        appraiserUser.setAppraiseTiesId(appraiseTiesId);
        appraiserUser.setAppraiseTies(score.getReviewerName());
        appraiserUser.setUserScore(score.getUserScore());

        double totalScore = 0.0;
        if (StringUtils.isNotBlank(score.getUserScore())) {
            // 从analyseListVos中获取权重
            double weightValue = 1.0; // 默认权重值
            for (AnalyseListVo analyseListVo : analyseListVos) {
                if (analyseListVo.getAssessedName().equals(score.getReviewerName())) {
                    for (AnalyseListVo.AppraiserUser user : analyseListVo.getAppraiserUser()) {
                        if (user.getAppraiserName().equals(score.getUserName())) {
                            String appraiseTiesStr = user.getAppraiseTies();
                            if (appraiseTiesStr != null) {
                                String numericString = appraiseTiesStr.replaceAll("\\D", "");
                                if (!numericString.isEmpty()) {
                                    weightValue = Double.parseDouble(numericString);
                                }
                            }
                            break;
                        }
                    }
                    break;
                }
            }

            List<Dimension> zf = appraiseMapper.selezf(score.getQuestionId());
            long avgSum = calculateFirstScores(zf);
            Weight weight = filterWeight(weights, matchedAppraiseList);


            double percentage = percentage(weight, (int) weightValue);
            System.out.println(percentage);
            List<String> strArray = Arrays.asList(score.getUserScore().split(","));

            long sum = 0;
            for (String str : strArray) {
                try {
                    sum += Long.parseLong(str);
                } catch (NumberFormatException e) {
                    continue;
                }
            }
            System.out.println("percentage：" + percentage);
            System.out.println("sum：" + sum);
            System.out.println("avgSum：" + avgSum);
            totalScore = percentage * sum / avgSum * 100 + 100 * (1 - percentage);
        }

        return totalScore;
    }

    private static void scoreSum(double[] newScore, double @NotNull [] score) {
        for (int i = 0; i < score.length - 1; i++) {
            score[i] = (score[i] + newScore[i]);
        }
    }

//    private static double percentage(List<WeightDataVo.WeightDataList> weight, Integer value) {
//
//        WeightDataVo.WeightDataList weightDataList = weight.stream().filter(res -> res.getAppraiseTiesId() == value).findFirst().orElse(null);
//
//        return weightDataList.getValued() / 100.0;
//    }

    private static double percentage(Weight weight, Integer value) {
        switch (value) {
            case 1://直接上级
                return weight.getLevel1() / 100.0;
            case 2://相关上级
                return weight.getLevel2() / 100.0;
            case 3://直接平级
                return weight.getLevel3() / 100.0;
            case 4://相关平级
                return weight.getLevel4() / 100.0;
            case 5://下级
                return weight.getLevel5() / 100.0;
            case 6://下级
                return weight.getLevel6() / 100.0;
            case 7://下级
                return weight.getLevel7() / 100.0;
            case 8://下级
                return weight.getLevel8() / 100.0;
            default:
                return 0.0;
        }
    }

    private static List<List<String>> createdHead(String[] headMap) {
        List<List<String>> headList = new ArrayList<>();
        for (String head : headMap) {
            List<String> list = new ArrayList<>();
            list.add(head);
            headList.add(list);
        }
        return headList;
    }

    public List<AnalyseListVo> getAnalyseListss(ScoreDto scoreDto , String ppraise ) {
        Map<String, Object> map = new HashMap<>();
        List<AnalyseListVo> maps = null;

        List<AnalyseListVo> analyseListVos = appraiseMapper.appraiseAnalyseList(scoreDto);
        List<Weight> weights = weightMapper.getInfo(scoreDto.getQuestionId());

        Appraise appraiseDto = new Appraise();
        appraiseDto.setQuestionId(scoreDto.getQuestionId());
        List<Appraise> appraiseList = appraiseMapper.countAppraiseList(appraiseDto);
        List<AnalyseListVo.AppraiserUser >appraiserUser1 = appraiseMapper.selectListquestionId(scoreDto.getQuestionId());

        analyseListVos.forEach(res -> {
            List<AnalyseListVo.AppraiserUser> appraiserUsers = res.getAppraiserUser();
            if (appraiserUsers == null || appraiserUsers.isEmpty()) {
                appraiserUsers = appraiserUser1;
                if (appraiserUsers == null || appraiserUsers.isEmpty()) {
                    return;
                }
            }

            for (AnalyseListVo.AppraiserUser appraiserUser : res.getAppraiserUser()) {
                Integer appraiseTiesId = appraiserUser.getAppraiseTiesId();
                String appraiseTies = appraiserUser.getAppraiseTies();
                Integer appraiseTiesIds = Integer.parseInt(appraiseTies.replaceAll("\\D", ""));
                appraiserUser.setAppraiseTiesId(appraiseTiesIds);
            }

            List<Appraise> collect = new ArrayList<>();
            for (Appraise appraise : appraiseList) {
                if (res.getAssessedId().equals(appraise.getAssessedId()) && StringUtils.isNotBlank(appraise.getUserScore())) {
                    collect.add(appraise);
                }
            }
            Weight weight = filterWeight(weights, collect);

            long completeNum = 0;
            double totalScore = 0.0;
            List<AnalyseListVo.AppraiserUser> appraiserUser2 = res.getAppraiserUser();

            for (AnalyseListVo.AppraiserUser appraiserUser : appraiserUser2) {
                if (StringUtils.isNotBlank(appraiserUser.getUserScore())){
                    double percentage2 = percentage(weight, appraiserUser.getAppraiseTiesId());
                    res.setQuanzhong(percentage2);
                }
//                System.out.println("开始计算总分");
                if (StringUtils.isNotBlank(appraiserUser.getUserScore()) ) {
                    System.out.println("用户得分不为空");
                    System.out.println("用户姓名："+appraiserUser.getAppraiserName());
                    completeNum++;
                    if (weight != null) {
                        System.out.println("权重也不为空");
                        List<Dimension> zf = appraiseMapper.selezf(ppraise);
                        long avgSum = calculateFirstScores(zf);

                        double percentage = percentage(weight, appraiserUser.getAppraiseTiesId());
                        List<String> strArray = Arrays.asList(appraiserUser.getUserScore().split(","));
                        // 得到不计算权重的总分
                        System.out.println("进入计算方法");
                        int sum = 0;
                        for (String str : strArray) {
                            System.out.println("str：" + str);

                            try {
                                sum += Integer.parseInt(str);
                            } catch (NumberFormatException e) {
                                continue; // 如果出现异常，跳过当前数据
                            }
                        }
                        System.out.println("percentage：" + percentage);
                        System.out.println("sum：" + sum);
                        System.out.println("avgSum：" + avgSum);
                        totalScore = percentage * sum / avgSum * 100  + 100 * (1 - percentage);
                        System.out.println("totalScore：" + totalScore);
                        res.setScoreTotal(totalScore);
                        res.setQuanzhong(percentage);

                    }
                }
            }
            res.setAppraiserUserCount(completeNum + "/" + res.getAppraiserUser().size());
        });
        return analyseListVos;
    }
}
